layui.config({}).extend({}).use(['jquery', 'form', 'laydate', 'element', "layer"], function () {
    var $ = layui.jquery
    var form = layui.form
    var laydate = layui.laydate
    var layer = layui.layer

    // 背景页的方法
    var getBackgroundPage = chrome.extension.getBackgroundPage();
    var actions = window.actions = getBackgroundPage.actions;
    var _local = window._local = getBackgroundPage._local;



    //监听提交-登录
    form.on('submit(formDemo)', function (data) {
        actions.login(data, layui);
        _local.setData("login", data.field)
        return false;
    });
    //监听提交-注册 
    form.on('submit(formDemo_register)', function (data) {
        actions.register(data)
        return false;
    });

    var popup = {
        openMsg(text, sendResponse) {
            layer.msg(text)
        },
        // 给登录form赋值。
        defaultLogin() {
            var loginValue = _local.getData('login');
            form.val('login', Object.assign({}, loginValue))
        },
        upload() {
            actions.setBookmarksData(function (res) {
                if (res.error)
                    popup.openMsg(res.error)
                else
                    popup.openMsg("上传数据")
            });
        },
        update() {
            if (_local.getData("bmob")) {
                actions.coverLocat2();
                popup.openMsg("更新数据")
            } else {
                popup.openMsg("请先登录！！！")
            }
        }
    }

    $('[data-type]').on('click', function () {
        var type = $(this).data('type');
        popup[type] ? popup[type].call(this, arguments) : '';
        return false;
    });

    window.popup = popup
    actions.getPopup();
})

// 监听来自content-script的消息
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    var openFn = request.openFn;
    var parameter = request.parameter;
    if (popup[openFn]) {
        popup[openFn](parameter, sendResponse)
        // popup.openMsg.apply(this, parameter)
    }
    // console.log(request, sender, sendResponse);
    // sendResponse('我是popup：现在向背景页发送信息');
});